package com.app.admin.controller;

import com.app.admin.service.SecurityService;
import com.app.admin.service.UserService;
import com.app.common.dto.LoginRequest;
import com.app.common.dto.RegisterRequest;
import com.app.common.entity.User;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@RequestMapping("/api/auth")
@Controller
public class AuthController {
    private UserService userService;
    private SecurityService securityService;

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    // 使用构造器注入，移除 @RequiredArgsConstructor
    @Autowired
    public AuthController(UserService userService, SecurityService securityService) {
        this.userService = userService;
        this.securityService = securityService;
    }

    // 显示注册页面
    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("registerRequest", new RegisterRequest());
        return "register";
    }

    // 处理注册请求
    @PostMapping("/register")
    public String register(@ModelAttribute RegisterRequest registerRequest,
                           Model model,
                           RedirectAttributes redirectAttributes) {
        try {
            // 验证密码确认
            if (!registerRequest.isPasswordMatch()) {
                model.addAttribute("error", "密码不匹配");
                return "/register";
            }

            // 创建用户
            User user = new User(registerRequest.getUsername(),
                    registerRequest.getEmail(),
                    registerRequest.getPassword());

            userService.registerUser(user);
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "redirect:/api/auth/login";

        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            return "/register";
        }
    }

    // 显示登录页面
    @GetMapping("/login")
    public String showLoginForm(Model model) {
        logger.info("showLoginForm begin");
        model.addAttribute("loginRequest", new LoginRequest());
        return "/login";
    }

    // 退出登录
    @PostMapping("/logout")
    public String logout() {
        SecurityContextHolder.clearContext();
        return "redirect:/api/auth/login?logout";
    }
}